<template>
  <view class="form-container">
    <!-- 图片上传 -->
    <view class="upload-section">
      <text>壁纸</text>
      <button @click="chooseImage">选择图片</button>
      <view v-for="(item, index) in formData.fileList" :key="index">
        <image
          :src="item.url"
          mode="widthFix"
          class="uploaded-image"
          @click="previewImage(index)"
        />
        <text @click="removeImage(index)" class="remove-text">删除</text>
      </view>
    </view>

    <!-- 描述输入框 -->
    <view class="input-section">
      <text>描述</text>
      <textarea v-model="formData.description" placeholder="请输入描述"></textarea>
    </view>

    <!-- 分类选择 -->
    <view class="select-section">
      <text>分类</text>
      <picker mode="selector" :range="categoryNames" range-key="name" @change="onCategoryChange">
        <view>{{ selectedCategoryName || '请选择分类' }}</view>
      </picker>
    </view>

    <!-- 标签管理 -->
    <view class="tags-section">
      <text>标签</text>
      <view v-for="tag in formData.tabs" :key="tag" class="tag-item">
        <view class="tag-item-content">
          <uni-tag :text="tag" type="primary" class="tag"></uni-tag>
          <text @click="handleClose(tag)" class="close-tag">x</text>
        </view>
      </view>
      <input
        v-if="inputVisible"
        ref="InputRef"
        v-model="inputValue"
        class="input-new-tag"
        @confirm="handleInputConfirm"
        @blur="handleInputConfirm"
      />
      <button v-else class="button-new-tag" @click="showInput">增加标签</button>
    </view>

    <!-- 提交按钮 -->
    <view class="button-container">
      <button type="primary" @click="submitForm">提交</button>
      <button @click="resetForm">重置</button>
    </view>
  </view>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue'
import { showConfirm, toast } from '@/utils/common'
import { apiGetCategoryNames, apiPostingWallpaper } from '@/api/tsApis'
import { getToken, getUserId, getUserName } from '@/utils/auth'
import { apiGetPostingDetail } from '@/api/apis'

// 获取父组件传递的id
const props = defineProps({
  id: {
    type: String,
    default: '',
  },
})
// 表单数据
const formData = reactive({
  description: '',
  classId: '',
  fileList: [],
  tabs: [],
})
const imgUrl = ref('')

// 分类选项
const categoryNames = ref([])
const selectedCategoryName = ref('')

// 获取分类名称
onMounted(async () => {
  const pId = Number(props.id)
  try {
    // 判断是否有id，如果有，则为编辑模式，否则为新增模式
    if (!isNaN(pId)) {
      const params = {
        id: pId,
        type: 1,
        userId: getUserId(),
      }
      const res = await apiGetPostingDetail(params)
      // console.log('res', res)
      if (res.code === 200) {
        const data = res.data
        formData.description = data.description
        formData.classId = data.classId
        selectedCategoryName.value = data.className
        formData.fileList = [
          {
            name: data.smallPicurl,
            url: data.smallPicurl,
          },
        ]
        formData.tabs = data.tabs.split(',') || []
      }
    }

    const res = await apiGetCategoryNames('1')
    categoryNames.value = res.data
  } catch (err) {
    console.error(err)
  }
})

// 分类选择变更处理
const onCategoryChange = (e) => {
  const index = e.detail.value
  formData.classId = categoryNames.value[index].id
  selectedCategoryName.value = categoryNames.value[index].name
}

// 图片上传相关逻辑
const chooseImage = async () => {
  const res = await uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
  })

  if (res.tempFilePaths.length > 0) {
    formData.fileList.push({
      name: res.tempFiles[0].name,
      url: res.tempFilePaths[0],
    })
  }
}

const removeImage = (index) => {
  showConfirm('确认删除该图片吗？').then(() => {
    formData.fileList.splice(index, 1)
  })
}

const previewImage = (index) => {
  uni.previewImage({
    urls: formData.fileList.map((item) => item.url),
    current: formData.fileList[index].url,
  })
}

const submitUpload = () => {
  formData.fileList.forEach((file, index) => {
    uni.uploadFile({
      url: import.meta.env.VITE_APP_ADMIN_URL + '/common/uploadOSS',
      filePath: file.url,
      name: 'file',
      formData: {
        fileName: file.name,
      },
      header: {
        Authorization: 'Bearer ' + getToken(),
      },
      success: (uploadRes) => {
        console.log('uploadRes', uploadRes)
        const response = JSON.parse(uploadRes.data)
        console.log(response)
        if (response.code === 200) {
          imgUrl.value = response.url
          console.log('imgUrl', imgUrl.value)
          toast(response.msg)
          // 准备提交的数据
          const wallpaperData = reactive({
            id: Number(props.id) || null,
            smallPicurl: imgUrl.value,
            description: formData.description,
            userId: getUserId(),
            classId: formData.classId,
            nickname: getUserName(),
            tabs: formData.tabs.join(','),
          })

          try {
            apiPostingWallpaper(wallpaperData).then((res) => {
              console.log('res', res)
              if (res.code === 200) {
                resetForm()
                toast('发布成功')
              }
            })
          } catch (err) {
            toast('发布失败')
            console.error(err)
          }
        }
      },
    })
  })
}

// 提交表单
const submitForm = async () => {
  console.log('formData', formData)
  if (!formData.description || !formData.classId || formData.fileList.length === 0) {
    toast('请填写完整信息')
    return
  }

  await submitUpload()
}

// 重置表单
const resetForm = () => {
  formData.description = ''
  formData.classId = ''
  formData.fileList = []
  formData.tabs = []
}

// 标签管理逻辑
const inputValue = ref('')
const inputVisible = ref(false)

const handleClose = (tag) => {
  formData.tabs.splice(formData.tabs.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    formData.tabs.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>
<style lang="scss" scoped>
.form-container {
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);

  .upload-section,
  .input-section,
  .select-section,
  .tags-section {
    margin-bottom: 20rpx;

    text {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 8rpx;
    }
  }

  button {
    background-color: #409eff;
    color: white;
    border: none;
    border-radius: 4rpx;
    padding: 10rpx 20rpx;
    cursor: pointer;
    transition: background-color 0.3s ease;

    &:hover {
      background-color: darken(#409eff, 10%);
    }
  }

  input,
  textarea {
    width: 100%;
    padding: 10rpx;
    box-sizing: border-box;
    border: 1rpx solid #dcdcdc;
    border-radius: 4rpx;
    font-size: 24rpx;
    outline: none;
    transition: border-color 0.3s ease;

    &:focus {
      border-color: #409eff;
    }
  }

  .tag-item {
    display: inline-block;
    background-color: #e6f7ff;
    color: #1890ff;
    padding: 4rpx 8rpx;
    border-radius: 16rpx;
    margin-right: 5rpx;
    font-size: 12rpx;
    .tag-item-content {
      display: flex;
      align-items: center;
    }

    .tag {
      margin-right: 5rpx;
    }

    .close-tag {
      margin-left: 4rpx;
      cursor: pointer;
      color: #ff4d4f;
    }
  }

  .input-new-tag {
    width: 100%;
    height: 60rpx;
    margin-top: 8rpx;
  }

  .button-new-tag {
    width: 100%;
    margin-top: 8rpx;
    background-color: #fff;
    color: #409eff;
    border: 1rpx solid #409eff;
    padding: 8rpx;

    &:hover {
      background-color: #e6f7ff;
    }
  }

  .button-container {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;

    button {
      flex-grow: 1;
      margin: 0 5rpx;
      padding: 12rpx 0;
      font-size: 32rpx;
    }
  }
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
  cursor: pointer;
}

.remove-text {
  color: #ff4d4f;
  cursor: pointer;
}
</style>
